﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using bdnt_pets_system.FailureServiceReference;
using bdnt_pets_system_Entity;
using bdnt_pets_system.Tools;
using bdnt_pets_system.PageViews.Failures;
using System.Collections.ObjectModel;
using System.Windows.Data;
using bdnt_pets_system.DataServiceReference;
using bdnt_pets_system.Resources;

namespace bdnt_pets_system.PageViews.FailuresTraking
{
    public partial class SaveTrakingControl : BaseUserControl
    {
        DataServiceReference.DataServiceClient dataClient;
        FailureServiceClient faiClient;
        int pageSize = SessionManager.PageSize;
        int currentPartPage = 1;
        int currentFaiultPage = 1;
        public Tbl_Part CuPartInfo;
        public Tbl_Part LastPartInfo;
        public SaveTrakingControl()
        {
            InitializeComponent();
            dataClient = new DataServiceReference.DataServiceClient();
            faiClient = new FailureServiceClient();
            InitData();
        }

        void InitData()
        {
            dpTrakingDate.SelectedDate = DateTime.Now;
            InitEvent();
            dataClient.GetPartListByConditionCountAsync(null);
        }

        void InitEvent()
        {
            #region PartInfo
            btnFjgxgz.Click += new RoutedEventHandler(btnFjgxgz_Click);
            hbXztd.Click += new RoutedEventHandler(hbXztd_Click);
            dataClient.GetPartListByConditionCompleted += new EventHandler<GetPartListByConditionCompletedEventArgs>(dataClient_GetPartListByConditionCompleted);
            dataClient.GetPartListByConditionCountCompleted += new EventHandler<GetPartListByConditionCountCompletedEventArgs>(dataClient_GetPartListByConditionCountCompleted);
            partPageC.dpPage.PageIndexChanged += new EventHandler<EventArgs>(dpPartPage_PageIndexChanged);
            tbPartName.KeyDown += new KeyEventHandler(tbPartName_KeyDown);
            #endregion

            #region FailureInfo
            dataClient.GetFailureInfoListByPartNoCompleted += new EventHandler<DataServiceReference.GetFailureInfoListByPartNoCompletedEventArgs>(dataClient_GetFailureInfoListByPartNoCompleted);
            dataClient.GetFailureInfoListByPartNoCountCompleted += new EventHandler<DataServiceReference.GetFailureInfoListByPartNoCountCompletedEventArgs>(dataClient_GetFailureInfoListByPartNoCountCompleted);
            fauiltPageC.dpPage.PageIndexChanged += new EventHandler<EventArgs>(dpPage_PageIndexChanged);
            btnSaveFauilre.Click += new RoutedEventHandler(btnSaveFauilre_Click);
            btnShowFauilre.Click += new RoutedEventHandler(btnShowFauilre_Click);
            faiClient.SaveFailureTrackingCompleted += new EventHandler<SaveFailureTrackingCompletedEventArgs>(faiClient_SaveFailureTrackingCompleted);
            tbFauilte.KeyDown += new KeyEventHandler(tbFauilteName_KeyDown);
            #endregion
        }

        void btnFjgxgz_Click(object sender, RoutedEventArgs e)
        {
            if (gdFjghgz.Visibility == System.Windows.Visibility.Collapsed)
            {
                gdJghgz.Visibility = System.Windows.Visibility.Collapsed;
                gdFjghgz.Visibility = System.Windows.Visibility.Visible;
                btnFjgxgz.Content = MyStrings.jgxgz;
            }
            else
            {
                gdJghgz.Visibility = System.Windows.Visibility.Visible;
                gdFjghgz.Visibility = System.Windows.Visibility.Collapsed;
                btnFjgxgz.Content = MyStrings.fjgxgz;

            }
        }

        #region PartInfo
        string partName = "";
        void tbPartName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                currentPartPage = 1;
                CuPartInfo = null;
                partName = tbPartName.Text;
                dataClient.GetPartListByConditionCountAsync(new Tbl_Part() { IsValidate = false, PartName = partName, en_PartName = partName });
            }
        }

        void dataClient_GetPartListByConditionCountCompleted(object sender, GetPartListByConditionCountCompletedEventArgs e)
        {
            partPageC.LoadPages(e.Result, pageSize);
        }

        void dpPartPage_PageIndexChanged(object sender, EventArgs e)
        {
            currentPartPage = partPageC.PageIndex + 1;
            dataClient.GetPartListByConditionAsync(new Tbl_Part() { IsValidate = false, PartName = partName, en_PartName = partName }, pageSize, currentPartPage);
        }

        ObservableCollection<Tbl_Part> cuConditionParts;
        void dataClient_GetPartListByConditionCompleted(object sender, GetPartListByConditionCompletedEventArgs e)
        {
            cuConditionParts = e.Result;
            LoadParts();
        }

        void LoadParts()
        {
            wpParts.Children.Clear();
            if (cuConditionParts == null || cuConditionParts.Count() < 1)
                return;
            foreach (var item in cuConditionParts)
            {
                Border bd = new Border();
                HyperlinkButton hb = new HyperlinkButton() { Tag = item };
                if (CuPartInfo != null && CuPartInfo.PartNo == item.PartNo)
                {
                    bd.BorderBrush = new SolidColorBrush(Colors.Red);
                    bd.Background = new SolidColorBrush(HelpTools.HtmlToColor("#D0D7E3"));
                }
                hb.DataContext = item;
                hb.Click += new RoutedEventHandler(parthb_Click);
                TextBlock tb = new TextBlock()
                {
                    Margin = new Thickness(5),
                    TextWrapping = TextWrapping.Wrap
                };

                tb.Text = SessionManager.IsCN_ZH ? item.PartName + "(" + item.en_PartName + ")" : item.en_PartName;
                hb.Content = tb;
                bd.Child = hb;
                wpParts.Children.Add(bd);
            }
        }

        void parthb_Click(object sender, RoutedEventArgs e)
        {
            var cuo = (sender as HyperlinkButton);
            CuPartInfo = cuo.Tag as Tbl_Part;
            if ((LastPartInfo != null && CuPartInfo.Id != LastPartInfo.Id) || LastPartInfo == null)
            {
                LoadParts();
                currentFaiultPage = 1;
                dataClient.GetFailureInfoListByPartNoCountAsync(CuPartInfo.PartNo, failName, failName);
            }
        }

        void hbXztd_Click(object sender, RoutedEventArgs e)
        {
            AddToTrakingWindow atw = new AddToTrakingWindow();
            atw.Show();
            atw.Closed += new EventHandler(atw_Closed);
        }

        public int zzTdId;
        public List<int> selectMemembers = new List<int>();
        void atw_Closed(object sender, EventArgs e)
        {
            var cuo = sender as AddToTrakingWindow;
            if (cuo.DialogResult == true)
            {
                zzTdId = cuo.zzTdId;
                selectMemembers = cuo.selectMemembers;
                tbZrr.Text = cuo.selectMembersName;
                tbTd.Text = cuo.zzTdName;
            }
        }

        #endregion

        #region FailureInfo
        string failName = "";
        void tbFauilteName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                currentFaiultPage = 1;
                selectFailure = null;
                failName = tbFauilte.Text;
                dataClient.GetFailureInfoListByPartNoCountAsync(CuPartInfo.PartNo, failName, failName);
            }
        }
        void dataClient_GetFailureInfoListByPartNoCountCompleted(object sender, DataServiceReference.GetFailureInfoListByPartNoCountCompletedEventArgs e)
        {
            fauiltPageC.LoadPages(e.Result, pageSize);
        }

        void dpPage_PageIndexChanged(object sender, EventArgs e)
        {
            currentFaiultPage = fauiltPageC.PageIndex + 1;
            dataClient.GetFailureInfoListByPartNoAsync(CuPartInfo.PartNo, failName, failName, pageSize, currentFaiultPage);
        }
        public SimpleObject<Tbl_FailureInfo, int> selectFailure = new SimpleObject<Tbl_FailureInfo, int>();

        ObservableCollection<Tbl_FailureInfo> AllFailures;
        void dataClient_GetFailureInfoListByPartNoCompleted(object sender, DataServiceReference.GetFailureInfoListByPartNoCompletedEventArgs e)
        {
            LastPartInfo = CuPartInfo;
            AllFailures = e.Result;
            selectFailure = null;
            InitFailus();
        }

        void InitFailus()
        {
            wpFailures.Children.Clear();
            if (AllFailures == null)
                return;
            foreach (var item in AllFailures)
            {
                Border bd = new Border()
                {
                    Margin = new Thickness(0, 0, 10, 10),
                    BorderThickness = new Thickness(0),
                    Width = 150,
                    MinHeight = 100,
                    //Background = new SolidColorBrush(HelpTools.HtmlToColor("#BBBBBB")),
                    Background = new SolidColorBrush(HelpTools.HtmlToColor("#E6EBF1"))
                };
                Grid gd = new Grid();
                gd.RowDefinitions.Add(new RowDefinition());
                gd.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                gd.ColumnDefinitions.Add(new ColumnDefinition());
                gd.ColumnDefinitions.Add(new ColumnDefinition());
                gd.ColumnDefinitions.Add(new ColumnDefinition());
                bd.Child = gd;
                InitFauiltLevel(item, bd);
                wpFailures.Children.Add(bd);
            }
        }

        void InitFauiltLevel(Tbl_FailureInfo item, Border bd)
        {
            Grid gd = bd.Child as Grid;
            gd.Children.Clear();

            TextBlock tb = new TextBlock() { Margin = new Thickness(5) };

            tb.Text = SessionManager.IsCN_ZH ? item.FailureName + "(" + item.en_FailureName + ")" : item.en_FailureName;
            Grid.SetColumnSpan(tb, 3);
            gd.Children.Add(tb);

            Border bdG = new Border() { Tag = bd };
            ToolTipService.SetToolTip(bdG, "此缺陷被添加过" + item.FailureGCount.ToString() + "次");
            HyperlinkButton fauilhbG = new HyperlinkButton()
            {
                //BorderBrush = new SolidColorBrush(Colors.LightGray), 
                BorderBrush = new SolidColorBrush(HelpTools.HtmlToColor("#EBF1F3")),
                Tag = new SimpleObject<Tbl_FailureInfo, int>() { Item1 = item, Item2 = 2 }
            };
            TextBlock tbG = new TextBlock() { Text = "FC 1" };
            fauilhbG.Content = tbG;
            bdG.Child = fauilhbG;
            Grid.SetRow(bdG, 1);
            gd.Children.Add(bdG);
            fauilhbG.Click += new RoutedEventHandler(fauilhb_Click);
            fauilhbG.MouseEnter += new MouseEventHandler(fauilhbG_MouseEnter);
            fauilhbG.MouseLeave += new MouseEventHandler(fauilhbG_MouseLeave);

            Border bdZ = new Border() { Tag = bd };
            ToolTipService.SetToolTip(bdZ, "此缺陷被添加过" + item.FailureZCount.ToString() + "次");
            HyperlinkButton fauilhbZ = new HyperlinkButton()
            {
                //BorderBrush = new SolidColorBrush(Colors.LightGray),
                BorderBrush = new SolidColorBrush(HelpTools.HtmlToColor("#EBF1F3")),
                Tag = new SimpleObject<Tbl_FailureInfo, int>() { Item1 = item, Item2 = 1 }
            };
            TextBlock tbZ = new TextBlock() { Text = "FC 2" };
            fauilhbZ.Content = tbZ;
            bdZ.Child = fauilhbZ;
            Grid.SetRow(bdZ, 1);
            Grid.SetColumn(bdZ, 1);
            gd.Children.Add(bdZ);
            fauilhbZ.Click += new RoutedEventHandler(fauilhb_Click);
            fauilhbZ.MouseEnter += new MouseEventHandler(fauilhbG_MouseEnter);
            fauilhbZ.MouseLeave += new MouseEventHandler(fauilhbG_MouseLeave);

            Border bdD = new Border() { Tag = bd };
            ToolTipService.SetToolTip(bdD, "此缺陷被添加过" + item.FailureDCount.ToString() + "次");
            HyperlinkButton fauilhbD = new HyperlinkButton()
            {
                //BorderBrush = new SolidColorBrush(Colors.LightGray),
                BorderBrush = new SolidColorBrush(HelpTools.HtmlToColor("#EBF1F3")),
                Tag = new SimpleObject<Tbl_FailureInfo, int>() { Item1 = item, Item2 = 0 }
            };
            TextBlock tbD = new TextBlock() { Text = "FC 2N" };
            fauilhbD.Content = tbD;
            bdD.Child = fauilhbD;
            Grid.SetRow(bdD, 1);
            Grid.SetColumn(bdD, 2);
            gd.Children.Add(bdD);
            fauilhbD.Click += new RoutedEventHandler(fauilhb_Click);
            fauilhbD.MouseEnter += new MouseEventHandler(fauilhbG_MouseEnter);
            fauilhbD.MouseLeave += new MouseEventHandler(fauilhbG_MouseLeave);

            if (selectFailure != null && selectFailure.Item1 != null && selectFailure.Item1.Id == item.Id)
            {
                bd.Background = new SolidColorBrush(HelpTools.HtmlToColor("#D0D7E3"));
                //bd.Background = new SolidColorBrush(Colors.Gray);
                if (selectFailure.Item2 == 0)
                {
                    //bdD.Background = new SolidColorBrush(Colors.Gray);
                    bdD.Background = new SolidColorBrush(HelpTools.HtmlToColor("#D0D7E3"));
                    bdD.BorderBrush = new SolidColorBrush(Colors.Red);
                }
                else if (selectFailure.Item2 == 1)
                {
                    //bdZ.Background = new SolidColorBrush(Colors.Gray);
                    bdZ.Background = new SolidColorBrush(HelpTools.HtmlToColor("#D0D7E3"));
                    bdZ.BorderBrush = new SolidColorBrush(Colors.Red);
                }
                else if (selectFailure.Item2 == 2)
                {
                    //bdG.Background = new SolidColorBrush(Colors.Gray);
                    bdG.Background = new SolidColorBrush(HelpTools.HtmlToColor("#D0D7E3"));
                    bdG.BorderBrush = new SolidColorBrush(Colors.Red);
                }
            }
            else bd.Background = new SolidColorBrush(HelpTools.HtmlToColor("#E6EBF1"));
        }

        void fauilhbG_MouseLeave(object sender, MouseEventArgs e)
        {
            var cuo = sender as HyperlinkButton;
            var bd = cuo.Parent as Border;
            if ((bd.BorderBrush as SolidColorBrush).Color != Colors.Red)
            {
                bd.Background = cuo.BorderBrush;
                bd.BorderBrush = cuo.BorderBrush;
            }
        }

        void fauilhbG_MouseEnter(object sender, MouseEventArgs e)
        {
            var cuo = sender as HyperlinkButton;
            var bd = cuo.Parent as Border;
            if ((bd.BorderBrush as SolidColorBrush).Color != Colors.Red)
            {
                bd.BorderBrush = bd.Background = new SolidColorBrush(HelpTools.HtmlToColor("#D0D7E3"));
                //bd.BorderBrush = bd.Background = new SolidColorBrush(Colors.Gray);
            }
        }

        void fauilhb_Click(object sender, RoutedEventArgs e)
        {
            var cuo = sender as HyperlinkButton;
            var cuD = cuo.Tag as SimpleObject<Tbl_FailureInfo, int>;
            var bd = (cuo.Parent as Border).Tag as Border;

            if (!(selectFailure != null && selectFailure.Item1 != null && selectFailure.Item1.Id == cuD.Item1.Id && selectFailure.Item2 == cuD.Item2))
            {
                selectFailure = cuD;
                InitFailus();
            }

        }

        #endregion

        #region else event
        void btnShowFauilre_Click(object sender, RoutedEventArgs e)
        {
            var cur = new FailureTrackingManagerControl() { PreBaseUserControl = this.Tag as NewTrakingControl };
            cur.btnBack.Visibility = System.Windows.Visibility.Visible;
            App.ToNextPage(cur);
        }

        void btnSaveFauilre_Click(object sender, RoutedEventArgs e)
        {
            if (!BindgExpression())
                return;


            Tbl_FailureTracking ft = new Tbl_FailureTracking()
            {
                //FailureId = selectFailure.Item1.Id,
                //PartNo = CuPartInfo.PartNo, 
                PhaseNo = "1",
                Status = true,
                TeamId = zzTdId,
                TrackingDate = DateTime.Now,
                ToEmpIds = string.Join(",", selectMemembers),
                FailureLevel = selectFailure.Item2,
                TrackingEndDate = dpEndTrakingDate.SelectedDate.Value,
                RecorderUserId = SessionManager.CurrentUser.Id,
                RecordTime = DateTime.Now
            };
            if (btnFjgxgz.Visibility == System.Windows.Visibility.Collapsed)
            {
               ft.FailureId = selectFailure.Item1.Id;
               ft.PartNo = CuPartInfo.PartNo;
            }
            else
            {
                ft.FailureName = tbGzmc.Text;
            }
            faiClient.SaveFailureTrackingAsync(ft);
        }

        public bool BindgExpression()
        {
            if (!dpTrakingDate.SelectedDate.HasValue)
            {
                tbErrors.Text = MyStrings.qxzzzrq;
                return false;
            }
            if (!dpEndTrakingDate.SelectedDate.HasValue)
            {
                tbErrors.Text = MyStrings.qxzzhzzrq; //"请选择最后追踪日期";
                return false;
            }
            if (zzTdId == 0)
            {
                tbErrors.Text = MyStrings.qxzzztd;// "请选择追踪团队";
                return false;
            }

            if (selectMemembers.Count < 1)
            {
                tbErrors.Text = MyStrings.qxzzrr;// "请选择责任人";
                return false;
            }

            if (gdFjghgz.Visibility == System.Windows.Visibility.Visible)
            {
                if (string.IsNullOrEmpty(tbGzmc.Text))
                {
                    tbErrors.Text = MyStrings.qsrgz;// "请输入故障";
                    return false;
                }
            }
            else
            {
                if(CuPartInfo==null)
                {
                    tbErrors.Text = MyStrings.qxzbj;// "请选择故障";
                    return false;
                }
                if (selectFailure == null || selectFailure.Item1 == null)
                {
                    tbErrors.Text = MyStrings.qxzgz;// "请选择故障";
                    return false;
                }
            }

            return true;
        }
        void faiClient_SaveFailureTrackingCompleted(object sender, SaveFailureTrackingCompletedEventArgs e)
        {
            if (e.Result)
            {
                var cur = new FailureTrackingManagerControl();
                App.ToPage(cur);
            }
        }

        #endregion

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            var cuObj = (sender as HyperlinkButton);

        }
    }
}
